package com.lingnan.mqlistener;

import com.lingnan.config.NotificationWebSocketHandler;
import com.lingnan.entity.NotificationDTO;
import com.lingnan.entity.NotificationEntity;
import com.lingnan.entity.WebSocketMessage;
import com.lingnan.mapper.NotificationMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

// NotificationConsumer.java
@Component
@Slf4j
public class NotificationConsumer {
    
    @Autowired
    private NotificationWebSocketHandler webSocketHandler;
    
    @Autowired
    private NotificationMapper notificationMapper;
    
    @RabbitListener(queues = "${notification.queue}")
    public void handleNotification(NotificationEntity notification) {
        try {
            log.info("处理通知消息: {}", notification.getId());
            
            if (notification.getReceiverType() == 2) {
                // 系统公告，发送给所有在线用户
                NotificationDTO dto = convertToDTO(notification);
                WebSocketMessage message = WebSocketMessage.notification(null, dto);
                webSocketHandler.sendMessageToAll(message);
            } else {
                // 个人通知，发送给指定用户
                NotificationDTO dto = convertToDTO(notification);
                WebSocketMessage message = WebSocketMessage.notification(notification.getReceiverId(), dto);
                webSocketHandler.sendMessageToUser(notification.getReceiverId(), message);
            }
            
        } catch (Exception e) {
            log.error("处理通知消息失败", e);
        }
    }
    
    private NotificationDTO convertToDTO(NotificationEntity entity) {
        NotificationDTO dto = new NotificationDTO();
        dto.setId(entity.getId());
        dto.setSenderId(entity.getSenderId());
        dto.setReceiverId(entity.getReceiverId());
        dto.setReceiverType(entity.getReceiverType());
        dto.setTitle(entity.getTitle());
        dto.setContent(entity.getContent());
        dto.setType(entity.getType());
        dto.setStatus(entity.getStatus());
        dto.setCreatedAt(entity.getCreatedAt());
        dto.setReadAt(entity.getReadAt());
        return dto;
    }
}